﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using ProjetoComperio.BusinessLogicLayer;
using ProjetoComperio.WebServices.Entities;

namespace ProjetoComperio.WebServices.Services
{
    public class ContributionService : IContributionService
    {
        ContributionBLL contributionBLL;
        private EventBLL eventBLL;

        #region Constructor
        public ContributionService()
        {
            contributionBLL = new ContributionBLL();
            eventBLL = new EventBLL();
        }

        #endregion

        #region SearchContributions
        public List<Contribution> SearchContributions(string keyword, int rows)
        {
            List<Contribution> contributions = new List<Contribution>();
            var foundContributions = contributionBLL.SearchContributions(keyword, rows).ToList();
            contributionBLL.Dispose();
            foreach (var rawContribution in foundContributions)
            {
                contributions.Add(BuildContribution(rawContribution));
            }
            return contributions;
        }
        #endregion

        #region Contribution

        public Contribution RetrieveContribution(int contributionID)
        {
            return BuildContribution(contributionBLL.RetrieveContribution(contributionID));
        }
        #endregion

        #region Event
        public Event RetrieveEvent(int eventID)
        {
            return BuildEvent(eventBLL.RetrieveEvent(eventID));
        }

        #endregion

        #region Additional Methods
        private Contribution BuildContribution(ProjetoComperio.DataLayer.Entities.Contribution rawContribution)
        {
            eventBLL = new EventBLL();
            Contribution contribution = new Contribution();
            contribution.ContributionID = rawContribution.ContributionID;
            contribution.Description = rawContribution.Description;
            contribution.Title = rawContribution.Title;
            contribution.RegisterDate = rawContribution.RegisterDate;
            contribution.IsEvent = eventBLL.RetrieveEvent(rawContribution.ContributionID) != null;
            eventBLL.Dispose();
            return contribution;
        }
        private Event BuildEvent(ProjetoComperio.DataLayer.Entities.Event rawEvent)
        {
            Event _event = new Event();
            _event.Author = rawEvent.Author;
            _event.ContributionID = rawEvent.ContributionID;
            _event.Description = rawEvent.Description;
            _event.IsEvent = true;
            _event.Location = rawEvent.Location;
            _event.RegisterDate = rawEvent.RegisterDate;
            _event.Subject = rawEvent.Subject;
            _event.Title = rawEvent.Title;
            return _event;

        }

        #endregion
    }
}